<!-- 扫码点餐商品规格 -->
<template>
    <u-popup :show="show" :round="10" mode="center" closeable @close="close">
        <view class="specsPop viewboxs p-top20 d-flex f-column">
            <view class="size36 bold padding40">{{ currItem.name }}</view>
            <view class="list flex-1 p-left40 p-right40">
                <view class="m-bot20" v-for="(item,index) in specsList" :key="index">
                    <view class="size28 bold m-bot20">{{ item.title }}</view>
                    <view class="d-flex f-wrap">
                        <view class="specsTag text-center size26 color_33 bor_radius_6" v-for="(itm,idx) in item.list" :key="idx"
                            :class="{'active': specs_ids[index] == itm.specs_id, 'color_cc': !itm.state}"
                            @click="handleSpecs(index,itm.state,itm.specs_id)">{{ itm.title }}</view>
                    </view>
                </view>
            </view>
            <view class="line padding20-40 size26 color_33">已选规格：{{ currSpecs.specs_title }}</view>
            <view class="footer padding40 d-flex j-sb a-center">
                <view class="color_E9 bold">
                    <text class="size28">￥</text>
                    <text class="size40">{{ currSpecs.price || currItem.price }}</text>
                </view>
                <view class="d-flex a-center" v-if="counter">
                    <text class="iconfont icon-jianshao1 size40" @click="handleDel"></text>
                    <view class="amount size26 color_33 text-center">{{counter.num}}</view>
                    <text class="iconfont icon-zengjia size40" @click="handleAdd"></text>
                </view>
                <view class="botBtn bor_radius_10 flexac size28 white t-letter4" @click="handleSubmit" v-else>加入购物车</view>
            </view>
        </view>
    </u-popup>
</template>

<script>
    export default {
        props: {
            currItem: {
                type: Object,
                default: () => ({})
            },
            cartList: {
                type: Array,
                default: () => []
            }
        },
        data() {
            return {
                show: false,
                specsList: [], // 规格列表
                specsPrice: [],
                specsCopy: '', // 原始数据字符串
                specs_ids: [],
                currSpecs: '',
                counter: ''
            }
        },
        computed: {
            incCount(){ // 当前商品某规格是否被加购
                // if(!this.specs_ids.length) return
                let empty = this.specs_ids.findIndex(id=>!id)
                if(empty != -1) return this.counter = ''
                let result = this.cartList.find(n => n.operation_id == this.currSpecs.id)
                this.counter = result ? result : ''
            }
        },
        mounted() {
            this.getSpecs()
        },
        methods: {
            close() {
                this.$emit('close')
            },
            getSpecs() {
                this.$showLoading('')
				this.$http.post({
					url: '/publicPlugins/getGoodsSpcInfo',
					data: {
						goods_id: this.currItem.goods_id,
						shop_id: this.currItem.store_id || ''
					}
				}).then(res => {
                    this.$hideLoading()
					if (res.code != 100) return this.$Toast(res.msg)
                    this.show = true
					let getGoodsSpecs = res.data
					if (!getGoodsSpecs) return
					let { specsList, specsPrice} = getGoodsSpecs
					if (specsList && specsPrice) {
						this.specsList = specsList
                        this.specsPrice = specsPrice
						this.specsCopy = JSON.stringify(this.specsList)
						let first = specsPrice.find(item => item.stock > 0) // 接口返回的specs_ids默认从小到大排序
						if (first) {
							specsList.forEach((item, index) => {
								// 强制按照规格类别排序且个数一致
								let obj = item.list.find(itm => first.specs_ids.includes(itm.specs_id))
								this.specs_ids[index] = obj ? obj.specs_id : ''
							})
							this.currSpecs = first
						}
					}
				})
			},
            handleSpecs(index,itmState,id){ // 类别索引,规格状态,规格id
                let ids = JSON.parse(JSON.stringify(this.specs_ids))
                if(!itmState) return // 禁选
                if(ids[index] == id) return // 已选
                
                ids[index] = id
                let empty = ids.filter(id=>!id)

                if(!empty.length){ // 已选完
                    let up = ids.slice().sort((a,b)=>a-b)
                    let current = this.specsPrice.find(n => n.specs_ids == up.toString())
                    if(current){
                        this.specs_ids = ids // 更新视图
                        this.currSpecs = current
                        // 当前所选类别有无禁选规格，无则还原list
                        let result = this.specsList[index].list.find(item=>!item.state)
                        if(!result) this.specsList = JSON.parse(this.specsCopy)
                    } else{ // 没找到为undefined
                        this.specs_ids = ids.map(n => n == id ? id : '') // 只保留当前所选规格，其余类别规格id清空
                    }
                } else if(empty.length == 1){ // 仅剩一个类别未选，需判断该类别有无禁选规格
                    this.specs_ids = ids
                    // 未选类别索引
                    let i = ids.findIndex(id=>!id)
                    this.specsList[i].list.forEach(item=>{
                        let arr = JSON.parse(JSON.stringify(ids))
                        arr[i] = item.specs_id // 每一项规格组合
                        let result = this.specsPrice.find(itm=>itm.specs_ids == arr.sort((a,b)=>a-b).toString())
                        item.state = result ? true : false
                    })
                } else {
                    this.specs_ids = ids
                }
            },
            handleDel() {
                this.$emit('delBtn', this.counter.car_id)
            },
            handleAdd() {
                this.$emit('addBtn', this.counter.car_id)
            },
            handleSubmit(){
                let empty = this.specs_ids.findIndex(id=>!id)
                if(empty != -1) return this.$Toast('请选择规格')
                this.$emit('joinCart', {
                    ...this.currItem,
                    currSpecs: this.currSpecs
                })
                this.close()
            }
        }
    }
</script>

<style lang="scss" scoped>
    .specsPop {
        min-height: 50vh;
        max-height: 70vh;
        .list {
            overflow-x: hidden;
            overflow-y: auto;
        }
        .specsTag {
            min-width: 144rpx;
            line-height: 54rpx;
            padding: 0 10rpx;
            background: #F4F4F4;
            margin: 0 20rpx 20rpx 0;
            &.active {
                background: var(--color);
                color: white;
            }
        }
        .line {
            background: #fafafa;
            border: 2rpx solid #f0f0f0;
        }
        .footer {
            height: 160rpx;
        }
        .botBtn {
            width: 200rpx;
            height: 60rpx;
            background: var(--color);
        }
    }
    .amount {
        width: 60rpx;
    }
</style>